<script setup lang="ts">
import {
useBanComment,
useCommentList,
useRemoveTag,
useReportDict,
useSaveTag,
useTabCount,
useUpdateComment,
} from "@fl/api/xf-api/comment-manage";
import { SearchForm, SearchTable } from "@fl/components";
import { useMessage } from "@fl/hooks/web/use-message";
import type { TabsPaneContext } from "element-plus";
import { cloneDeep } from "lodash-es";
import type { PlusColumn } from "plus-pro-components";
import type { VxeGridProps, VxePagerEvents } from "vxe-table";
import ChooseBanTimeDialog from "./components/chooseBanTimeDialog.vue";
import DetailDialog from "./components/detailDialog.vue";
import TagsDialog from "./components/tagsDialog.vue";
import TagsManageDialog from "./components/tagsManageDialog.vue";

const { createConfirmModal, createMessage } = useMessage();
const HIDE_DICT = {
  1: {
    status: 2,
    tooltipLabel: "确认隐藏评论",
  },
  2: {
    status: 1,
    tooltipLabel: "确认显示评论",
  },
  3: {
    status: 3,
    tooltipLabel: "确认删除评论",
  },
};
const TOPUP_DICT = {
  1: {
    status: 2,
    tooltipLabel: "确认置顶评论",
  },
  2: {
    status: 1,
    tooltipLabel: "确认取消置顶评论",
  },
};
const AUDIT_DICT = {
  1: {
    status: 1,
    tooltipLabel: "确认通过已选评论",
  },
  2: {
    status: 2,
    tooltipLabel: "确认忽略已选评论",
  },
};
const tableRef = ref();
const tagsDialogRef = ref();
const banTimeDialogRef = ref();
const activeName = ref(2);
const commentStatus = ref<any>(2);
const commentType = ref(1);
const banTimeVisible = ref(false);
const tagsVisible = ref(false);
const tagsManageVisible = ref(false);
const detailVisible = ref(false);
const handleClick = (tab: TabsPaneContext) => {
  commentStatus.value = tab.props.name;
  tablePage.value.currentPage = 1;
};

type IState = {
  projectName?: string;
  commentContent?: string;
  timeRange?: any;
  commentType?: number;
  commentStatus?: number;
};
const initialState = {
  projectName: "",
  commentContent: "",
  timeRange: [],
  commentType: 1, //1楼盘 2文章
};
const state = ref<IState>(cloneDeep(initialState));

const ids = ref([]);

const initialPage = {
  currentPage: 1,
  pageSize: 10,
  total: 0,
};
const tablePage = ref(cloneDeep(initialPage));
const params = computed(() => ({
  pageNum: tablePage.value.currentPage,
  pageSize: tablePage.value.pageSize,
  ...state.value,
  commentStatus: activeName.value,
}));

const records = ref();
const { data, isLoading } = useCommentList(params);
const { data: tabCount, isLoading: tabCountLoading } = useTabCount(params);
const { mutate: updateMutate } = useUpdateComment();
const { mutate: banMutate } = useBanComment();
const { data: reportTypeDict, isLoading: dictLoading } = useReportDict();
function formatTabCount(tab) {
  if (tabCount.value) {
    return tabCount.value.find((item) => item.code == tab).count;
  } else {
    return 0;
  }
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
  tablePage.value.currentPage = currentPage;
  tablePage.value.pageSize = pageSize;
};
let finalOptions = reactive<VxeGridProps>({
  columns: [
    { type: "checkbox", width: 50 },
    { field: "projectName", title: "楼盘名称" },
    { field: "commentContent", title: "评论内容" },
    {
      field: "cbCommentPicLinkList",
      slots: { default: "cbCommentPicLinkList" },
      title: "评论图片",
    },
    { field: "userName", title: "用户名" },
    { field: "thumbsUp", title: "被赞" },
    { field: "parentId", slots: { default: "parentId" }, title: "评论类型" },
    { field: "commentDate", title: "评论时间" },
    { field: "cbCommentTagList", slots: { default: "cbCommentTagList" }, title: "标签" },
    { slots: { default: "operate" }, title: "操作", width: 250 },
  ],
});

watchEffect(() => {
  if (data.value) {
    records.value = cloneDeep(data.value.records);
    tablePage.value.total = data.value.total!;
    finalOptions = commentStatus.value === 3 ? reportColumns : defaultGridOptions;
  }
});
const columns: PlusColumn[] = [
  {
    label: "评论渠道",
    prop: "commentType",
    options: [
      {
        label: "楼盘评论",
        value: 1,
      },
      {
        label: "文章评论",
        value: 2,
      },
    ],
  },
  {
    label: "楼盘名称",
    prop: "projectName",
  },
  {
    label: "评论内容",
    prop: "commentContent",
  },
  {
    fieldProps: {
      endPlaceholder: "结束日期",
      format: "YYYY-MM-DD",
      startPlaceholder: "开始日期",
      type: "daterange",
      valueFormat: "YYYY-MM-DD",
    },
    label: "评论时间",
    valueType: "date-picker",
    prop: "timeRange",
  },
];
const reportColumns = reactive<VxeGridProps>({
  columns: [
    { type: "checkbox", width: 50 },
    { field: "projectName", title: "楼盘名称" },
    { field: "commentContent", title: "评论内容" },
    {
      field: "cbCommentPicLinkList",
      slots: { default: "cbCommentPicLinkList" },
      title: "评论图片",
    },
    { field: "userName", title: "用户名" },
    { field: "thumbsUp", title: "被赞" },
    { field: "parentId", slots: { default: "parentId" }, title: "评论类型" },
    { field: "commentDate", title: "评论时间" },
    { field: "cbCommentTagList", slots: { default: "cbCommentTagList" }, title: "标签" },
    {
      field: "cbCommentReport",
      slots: { default: "cbCommentReport" },
      title: "举报内容",
    },
    { slots: { default: "operate" }, title: "操作", width: 250 },
  ],
});
const defaultGridOptions = reactive<VxeGridProps>({
  columns: [
    { type: "checkbox", width: 50 },
    { field: "projectName", title: "楼盘名称" },
    { field: "commentContent", title: "评论内容" },
    {
      field: "cbCommentPicLinkList",
      slots: { default: "cbCommentPicLinkList" },
      title: "评论图片",
    },
    { field: "userName", title: "用户名" },
    { field: "thumbsUp", title: "被赞" },
    { field: "parentId", slots: { default: "parentId" }, title: "评论类型" },
    { field: "commentDate", title: "评论时间" },
    { field: "cbCommentTagList", slots: { default: "cbCommentTagList" }, title: "标签" },
    { slots: { default: "operate" }, title: "操作", width: 250 },
  ],
});
function reset() {
  state.value = initialState;
  tablePage.value = initialPage;
}
function submit(values: any) {
  if (values?.timeRange?.length > 0) {
    values.commentDateStart = `${values?.timeRange[0]} 00:00:00`;
    values.commentDateEnd = `${values?.timeRange[1]} 23:59:59`;
  }
  state.value = { ...values };
  state.value.commentType = commentType.value;
  tablePage.value.currentPage = 1;
}
function update(id: any, key, v) {
  const params = {
    idList: [id],
    // displayFlag: Number(HIDE_DICT[v].status),
  };
  params[key] =
    key === "topUp" ? Number(TOPUP_DICT[v].status) : Number(HIDE_DICT[v].status);
  createConfirmModal({
    content: `是否${
      key === "topUp" ? TOPUP_DICT[v].tooltipLabel : HIDE_DICT[v].tooltipLabel
    }？`,
    onError: () => {
      console.log("操作取消！");
    },
    onSuccess: () => {
      updateMutate(params, {
        onSuccess: () => {
          ElMessage.success("操作成功");
        },
      });
    },
  });
}
function audit(v, id) {
  const params = {
    idList: [],
    commentStatus: 2,
    displayFlag: v,
  };
  if (id === "list") {
    const $table = tableRef.value?.tableInstance;
    if ($table) {
      const selectRecords = $table.getCheckboxRecords();
      ids.value = selectRecords.map((item) => item.id);
      if (selectRecords.length) {
        params.idList = ids.value;
      } else {
        createMessage.warning("请至少选择一条评论");
        return;
      }
    }
  } else {
    params.idList = [id];
  }
  createConfirmModal({
    content: `是否${AUDIT_DICT[v].tooltipLabel}？`,
    onError: () => {
      console.log("操作取消！");
    },
    onSuccess: () => {
      updateMutate(params, {
        onSuccess: () => {
          ElMessage.success("操作成功");
        },
      });
    },
  });
}

// 评论列表标签展示
function tagArr(list: any) {
  return list.map((item: any) => item.name).join(",");
}
// 打标签
function saveTag() {
  const $table = tableRef.value?.tableInstance;
  if ($table) {
    const selectRecords = $table.getCheckboxRecords();
    ids.value = selectRecords.map((item) => item.id);
    const isAllParent = selectRecords.some((item) => item.parentId != 0);
    if (isAllParent) {
      createMessage.warning("回复类型不支持打标签");
      return;
    }
    if (selectRecords.length) {
      tagsVisible.value = true;
    } else {
      createMessage.warning("请至少选择一条评论");
    }
  }
}
const clearSelectEvent = () => {
  const $table = tableRef.value?.tableInstance;
  if ($table) {
    $table.clearCheckboxRow();
    ids.value = [];
  }
};

const { mutate: useSaveTagMutate } = useSaveTag();
const { mutate: useRemoveTagMutate } = useRemoveTag();
function confirmTag(taglist) {
  const params = {
    commentIdList: ids.value,
    tagIdList: taglist.map((item) => item.id),
  };
  createConfirmModal({
    content: "是否确认对已选评论打标签?",
    onError: () => {},
    onSuccess: () => {
      useSaveTagMutate(params, {
        onSuccess: () => {
          ElMessage.success("操作成功");
          // tagsVisible.value = false;
          clearSelectEvent();
          tagsDialogRef.value.close();
        },
      });
    },
  });
}
function confirmBanTime(time) {
  const params = {
    idList: ids.value,
    ban: 1,
    banEndTime: time,
  };
  createConfirmModal({
    content: "是否确认对已选评论用户进行禁言?",
    onError: () => {},
    onSuccess: () => {
      banMutate(params, {
        onSuccess: () => {
          ElMessage.success("操作成功");
          clearSelectEvent();
          banTimeDialogRef.value.close();
        },
      });
    },
  });
}
function cancelTag() {
  const $table = tableRef.value?.tableInstance;
  if ($table) {
    const selectRecords = $table.getCheckboxRecords();
    ids.value = selectRecords.map((item) => item.id);
    if (selectRecords.length) {
      createConfirmModal({
        content: "是否确认取消已选评论的标签?",
        onError: () => {},
        onSuccess: () => {
          useRemoveTagMutate(ids.value, {
            onSuccess: () => {
              ElMessage.success("操作成功");
              // tagsVisible.value = false;
              clearSelectEvent();
            },
          });
        },
      });
    } else {
      createMessage.warning("请至少选择一条评论");
    }
  }
}
function ban(id) {
  if (id === "list") {
    const $table = tableRef.value?.tableInstance;
    if ($table) {
      const selectRecords = $table.getCheckboxRecords();
      ids.value = selectRecords.map((item) => item.id);
      if (selectRecords.length) {
        banTimeVisible.value = true;
      } else {
        createMessage.warning("请至少选择一条评论");
        return;
      }
    }
  } else {
    ids.value = [id];
    banTimeVisible.value = true;
  }
}
const detail = ref({});
function showDetail(row) {
  detail.value = row;
  detail.value.reportTypeName = getLabel(
    row.cbCommentReport.reportType,
    reportTypeDict.value
  );
  detailVisible.value = true;
}
function getLabel(v, dict) {
  if (v) {
    return dict.find((i) => i.dictValue == v).dictLabel;
  } else {
    return "";
  }
}
function formatImg(arr: any) {
  if (!arr) {
    return [];
  }
  return arr.map((item: any) => item.picUrl);
}
</script>

<template>
  <ElCard class="mb-20" shadow="never">
    <SearchForm
      submit-text="搜索"
      v-bind="state"
      :columns="columns"
      @reset="reset"
      @submit="submit"
    >
      <template #plus-field-commentType>
        <el-select v-model="commentType">
          <el-option
            v-for="i in columns[0].options"
            :key="i.value"
            :label="i.label"
            :value="i.value"
          />
        </el-select>
      </template>
    </SearchForm>
  </ElCard>
  <ElCard shadow="never">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane :label="`全部评论(${formatTabCount(1)})`" :name="2"></el-tab-pane>
      <el-tab-pane :label="`待审核(${formatTabCount(2)})`" :name="1"></el-tab-pane>
      <el-tab-pane :label="`被举报(${formatTabCount(3)})`" :name="3"></el-tab-pane>
    </el-tabs>
    <SearchTable
      ref="tableRef"
      v-bind="finalOptions"
      v-model:pager="tablePage"
      :loading="isLoading || tabCountLoading || dictLoading"
      :data="records"
      @page-change="handlePageChange"
    >
      <template #toolbar_buttons>
        <el-button type="primary" @click="saveTag"> 打标签 </el-button>
        <el-button plain type="primary" @click="cancelTag"> 取消标签 </el-button>
        <el-button plain type="primary" @click="tagsManageVisible = true">
          标签管理
        </el-button>
        <el-button v-if="commentStatus === 1" type="primary" @click="audit(1, 'list')">
          通过
        </el-button>
        <el-button
          v-if="commentStatus === 1"
          plain
          type="primary"
          @click="audit(2, 'list')"
        >
          忽略
        </el-button>
        <el-button v-if="commentStatus !== 2" plain type="primary" @click="ban('list')">
          禁言
        </el-button>
      </template>
      <template #cbCommentPicLinkList="{ row }">
        <div v-if="row.cbCommentPicLinkList.length > 0">
          <el-badge :value="row.cbCommentPicLinkList.length" class="item">
          <ElImage
            :src="formatImg(row.cbCommentPicLinkList)[0]"
            class="w-full h-full"
            :preview-src-list="formatImg(row.cbCommentPicLinkList)"
            :initial-index="0"
          />
          </el-badge>
        </div>
      </template>
      <template #parentId="{ row }">
        {{ row.parentId == 0 ? "评论" : "回复" }}
      </template>
      <template #cbCommentTagList="{ row }">
        {{ tagArr(row.cbCommentTagList) }}
      </template>
      <template #cbCommentReport="{ row }">
        <div style="color: #da0004" @click="showDetail(row)" class="cursor-pointer">
          <div>
            <el-tag type="warning">
              {{ getLabel(row.cbCommentReport?.reportType, reportTypeDict) }}
            </el-tag>
          </div>
          <div>
            {{ row.cbCommentReport?.reportContent }}
          </div>
        </div>
      </template>
      <template #operate="{ row }">
        <el-button
          text
          type="primary"
          @click="update(row.id, 'displayFlag', row.displayFlag)"
          v-if="commentStatus !== 1"
        >
          {{ row.displayFlag === 1 ? "隐藏" : "显示" }}
        </el-button>

        <el-button
          v-if="commentStatus !== 1"
          text
          @click="update(row.id, 'displayFlag', 3)"
        >
          删除
        </el-button>
        <el-button
          v-if="commentStatus === 2"
          text
          @click="update(row.id, 'topUp', row.topUp)"
        >
          {{ row.topUp === 1 ? "取消置顶" : "置顶" }}
        </el-button>
        <el-button
          v-if="commentStatus === 1"
          text
          type="primary"
          @click="audit(1, row.id)"
        >
          通过
        </el-button>

        <el-button v-if="commentStatus === 1" text @click="audit(2, row.id)">
          忽略
        </el-button>
        <el-button v-if="commentStatus !== 2" text @click="ban(row.id)"> 禁言 </el-button>
      </template>
    </SearchTable>
  </ElCard>
  <TagsDialog v-model:show="tagsVisible" @confirm-tag="confirmTag" ref="tagsDialogRef" />
  <TagsManageDialog v-model:show="tagsManageVisible" />
  <ChooseBanTimeDialog
    v-model:show="banTimeVisible"
    @confirm-time="confirmBanTime"
    ref="banTimeDialogRef"
  />
  <DetailDialog v-model:show="detailVisible" v-model:detail="detail" />
</template>

<style lang="scss" scoped>
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
.item {
  margin-top: 10px;
  margin-right: 30px;
}
</style>
